package com.ogawa.joypal.distributionnetwork.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.net.wifi.ScanResult
import android.net.wifi.WifiManager
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SnackbarUtils
import com.easepal.softaplib.wifi.WiFiManager
import com.ogawa.base.base.BaseActivity
import com.ogawa.base.utils.AppUtil
import com.ogawa.base.utils.MiuiUtils
import com.ogawa.base.utils.OSUtils
import com.ogawa.base.utils.ToastUtil
import com.ogawa.joypal.distributionnetwork.R
import com.ogawa.joypal.distributionnetwork.widget.SoftApPopwindow
import com.ogawa.joypal.distributionnetwork.widget.SoftApPopwindowAdapter
import com.ogawa.projectcommon.constants.UrlPathConstant
import com.ogawa.projectcommon.utils.ProjectSpUtils
import com.yanzhenjie.permission.AndPermission
import kotlinx.android.synthetic.main.activity_net_config_input.*


@Route(path = UrlPathConstant.ACTIVITY_DISTRIBUTIONNETWORK_NET_INPUT)
class NetInputActivity : BaseActivity(), View.OnClickListener,
    SoftApPopwindowAdapter.OnItemClickListener {
    private lateinit var softApWindow: SoftApPopwindow
    private var isScanning = false
    private var scanResult: ScanResult? = null
    private var isUnRegister = false

    override fun getLayoutId(): Int {
        return R.layout.activity_net_config_input
    }

    override fun initView() {
        super.initView()
        setTitle(getString(R.string.connect_wifi_title))
        et_wifi_name.setOnClickListener(this)
        iv_psw_switch.setOnClickListener(this)
        findViewById<TextView>(R.id.tv_next).setOnClickListener(this)
        AppUtil.switchPasswordState(false, iv_psw_switch, et_wifi_psw)
        softApWindow = SoftApPopwindow(this, ArrayList(), this)
        WiFiManager.getInstance(this).registerBroadcastReceivers(this)
        WiFiManager.getInstance(this).setOnWifiScanResultsListener {
            dismissLoadingDialog()
            if (isScanning) {
                isScanning = false
                if (it.size == 0) {
                    //小米8需要打开GPS才能获取到列表
                    if (OSUtils.isMiui()) {
                        if (!AppUtil.checkGPSIsOpen(this)) {
                            SnackbarUtils.with(rootView)
                                .setMessage(getString(R.string.scanwifi_open_gps_tips)).show()
                        }
                    }
                    return@setOnWifiScanResultsListener
                }
                softApWindow.update(it)
                softApWindow.showPopupWindow(et_wifi_name)
            }

        }

//        val wifiName = getWIFIName(this)
//        et_wifi_name.text = wifiName
    }

    /**
     * 获取当前连接的wifi名称
     *
     * @param context
     * @return
     */
    private fun getWIFIName(context: Context): String {
        var ret = ""
        var wifiMgr = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
        wifiMgr?.let {
            var info = wifiMgr.getConnectionInfo()
            info?.let {
                if (it.networkId == -1){
                    ret = ""
                }else{
                    ret = it.ssid.replace("\"", "")
                }

            }
        }
        return ret
    }

    private fun scanWifi() {
        if (!WiFiManager.getInstance(this).isWifiEnabled) {
            ToastUtil.showToast(getString(R.string.open_wifi), Toast.LENGTH_SHORT)
            return
        }
        AndPermission.with(this)
            .runtime()
            .permission(
                Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.ACCESS_COARSE_LOCATION
            )
            .onGranted {
                if (!isScanning) {
                    isScanning = true
                    WiFiManager.getInstance(this).startScan()
                    showLoadingDialog(getString(R.string.waiting), canceledOnTouchOutside = false)
                }
            }.onDenied { }.start()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_psw_switch -> {
                AppUtil.switchPasswordState(!iv_psw_switch.isSelected, iv_psw_switch, et_wifi_psw)
            }
            R.id.tv_next -> {
                AndPermission.with(this)
                    .runtime()
                    .permission(
                        Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.CHANGE_WIFI_STATE
                    )
                    .onGranted {
                        if (scanResult == null) {
                            return@onGranted
                        }
                        val psw = et_wifi_psw.text.toString()
                        if (psw.isNotEmpty() && (psw.length < 8 || psw.length > 32)) {
                            ToastUtil.showToast(
                                getString(R.string.wifi_psw_error),
                                Toast.LENGTH_SHORT
                            )
                            return@onGranted
                        }
                        if (!WiFiManager.getInstance(this).isWifiEnabled) {
                            ToastUtil.showToast(getString(R.string.open_wifi), Toast.LENGTH_SHORT)
                            return@onGranted
                        }


                        val stratTime = System.currentTimeMillis()
                        val  mWifiManager = this.getApplicationContext()
                            .getSystemService(Context.WIFI_SERVICE) as WifiManager
                        val disconnect = mWifiManager!!.disconnect()
                        if (OSUtils.isMiui()){
                            var endTime = System.currentTimeMillis()
                            if (endTime - stratTime > 200  || !disconnect){
                                AlertDialog.Builder(mActivity)
                                    .setTitle(getString(R.string.set_wlan_authority_title))
                                    .setMessage(getString(R.string.set_wlan_authority_message))
                                    .setNegativeButton(R.string.cancel) { dialog, _ ->
                                        dialog.dismiss()
                                    }
                                    .setPositiveButton(R.string.confirm){dialog, _ ->
                                        MiuiUtils.jumpToPermissionsEditorActivity(this)
                                        dialog.dismiss()
                                    }
                                    .show()

                                return@onGranted
                            }
                        }

                        ProjectSpUtils.setProjectConfigWifiDeviceBean(
                            ProjectSpUtils.getProjectConfigWifiDeviceBean().also {
                                it.wifiName = scanResult?.SSID
                                it.wifiPwd = et_wifi_psw.text.toString()
                            })

                        WiFiManager.getInstance(this).onDestroy(this)
                        isUnRegister = true
                        val intent = Intent(this, NetConnectActivity::class.java)
                        intent.putExtra("scanResult", scanResult)
                        intent.putExtra("psw", psw)
                        startActivity(intent)
//                        finish()
                    }
                    .onDenied { }
                    .start()

            }
            R.id.et_wifi_name -> {
                if (softApWindow.data == null || softApWindow.data.size == 0) {
                    scanWifi()
                } else {
                    softApWindow.showPopupWindow(et_wifi_name)
                }
            }
        }
    }

    override fun onItemClick(scanResult: ScanResult?) {
        this.scanResult = scanResult
        softApWindow.dismissPopupWindow()
        et_wifi_name.text = scanResult!!.SSID
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!isUnRegister) {
            WiFiManager.getInstance(this).onDestroy(this)
        }
    }
}